package com.cheng.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cheng.dao.UavMapper;
import com.cheng.pojo.Location;
import com.cheng.pojo.Road;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/uav/user")
@Controller
public class UavController {
    @Autowired
    UavMapper uavMapper;

    @ResponseBody
    @RequestMapping("/hello")
    public String Hello(){
        return "hello";
    }

    @RequestMapping("/detail")
    public String list(Model model,String roadCrossing,String id,String node){
//        System.out.println(id+" "+roadCrossing+" "+node);
//        System.out.println(id+" "+"穿山"+" "+node);
        Map m=new HashMap();
        m.put("nowPage",0);
        m.put("limitPageInt",1);
        m.put("id",id);
        List<Road>list=uavMapper.getRoad(m);
        Map m1=new HashMap();
        if(roadCrossing==null||roadCrossing=="") {
            roadCrossing=list.get(0).getRoadcrossing();
            System.out.println(roadCrossing);
        }
        m1.put("roadCrossing",roadCrossing);
//        m1.put("roadCrossing","穿山");
        if(node=="")node=null;
        m1.put("node",node);
//        System.out.println(m1);
        List<Location>locations=uavMapper.getLocation(m1);

        model.addAttribute("roads",list);
        model.addAttribute("locations",locations);
        model.addAttribute("fileName",roadCrossing);
        model.addAttribute("imageName",roadCrossing);
//        System.out.println(id);
//        System.out.println(roadCrossing);
        return "detail";
    }

    @RequestMapping({"/","/index"})
    public String da(Model model,String roadCrossing,String nowPage,String limitPage,String id,String msg){
        if(msg!=null&&msg.equals("yes")) model.addAttribute("msg", "欢迎登陆!");
        //        System.out.println(nowPage+":nowPage ");
        int limitPageInt=9;
        if(limitPage!=null)limitPageInt=Integer.valueOf(limitPage);

        if(nowPage==null)nowPage="0";
        Map m=new HashMap();
        m.put("roadCrossing",roadCrossing);
//        System.out.println(roadCrossing);
        int count=uavMapper.getRoadCount(m).size();
//        System.out.println("count: "+count);

        int pageSize=count/limitPageInt+1;
        int now=Integer.parseInt(nowPage)<0?0:Integer.parseInt(nowPage);
        now=now>pageSize?pageSize:now;
        m.put("nowPage",now*limitPageInt);
        m.put("limitPageInt",limitPageInt);
        List<Road>list=uavMapper.getRoad(m);
        model.addAttribute("limitPage",limitPageInt);
        model.addAttribute("roads",list);
        model.addAttribute("nowPage",now);
        model.addAttribute("roadCrossing",roadCrossing);
        if(id==null)id="0";
        if(id=="")id="0";
        model.addAttribute("id",id);

//        System.out.println(roadCrossing);
        return "dashboard";
    }

    @RequestMapping("/download")
    public ResponseEntity uploaded(String fileName,String type) throws Exception{
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//
        System.out.println(fileName+type);
        //(1).文件只能放项目路径下
//        FileSystemResource file=new FileSystemResource(fileName+type);
//        InputStream inputStream=file.getInputStream();
//        (2).类加载器读取resours文件夹下的内容
//        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName+type);

//        (3).读取resours文件及以下的内容
        ClassPathResource classPathResource = new ClassPathResource("/public/dwg/"+fileName+type);
        System.out.println(classPathResource);
        InputStream inputStream =classPathResource.getInputStream();

//        File file=new File("D:\\BrokenMyth\\AStudyQueue\\juedui.txt");
//        ClassPathResource classPathResource = new ClassPathResource("/public/dwg/"+fileName+type);
//        System.out.println(classPathResource);
//        InputStream inputStream =new FileInputStream(file);

//        System.out.println(classPathResource.getFile().getAbsoluteFile());
//        System.out.println(file.getPath());
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition","attachment; "+"fileName="+fileName+type);
        return ResponseEntity.ok()
                .headers(headers)
//                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(inputStream));
    }


    @GetMapping("/downloadExcel")
    public void downloadTemplate(HttpServletResponse response) throws Exception {
        ClassPathResource classPathResource = new ClassPathResource("/public/excel/环城南一路与骖鸾路交叉口路宽提取.xlsx");
        InputStream inputStream = classPathResource.getInputStream();
        Workbook workbook = new XSSFWorkbook(inputStream);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode("环城南一路与骖鸾路交叉口路宽提取.xlsx", "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 导出数据
     */
    @GetMapping("/exportExcel")
    public void exportData(HttpServletResponse response,String roadCrossing,String type) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook();
        String []columnNames=null;
        if(type.equals("location"))
        columnNames = new String[]{"交叉路口坐标", "点号", "X值", "Y值", "经度", "纬度"};
        if(type.equals("road"))
        columnNames = new String[]{"交叉路口坐标", "道路名称", "顺序", "路宽", "车道类型", "车道方向"};

        Sheet sheet = workbook.createSheet();
        Font titleFont = workbook.createFont();
        titleFont.setFontName("simsun");
        titleFont.setBold(true);
        titleFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        titleStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        titleStyle.setFont(titleFont);

        Row titleRow = sheet.createRow(0);

        for (int i = 0; i < columnNames.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(columnNames[i]);
            cell.setCellStyle(titleStyle);
        }
        //模拟构造数据
        List dataList = new ArrayList<>();
        String s="";
        Map m=new HashMap();
        m.put("roadCrossing",roadCrossing);
        if(type.equals("location")) {
            dataList = uavMapper.getLocation(m);
            s = roadCrossing + "坐标.xls";
            //创建数据行并写入值
            for (int j = 0; j < dataList.size(); j++) {
                Location userExcelModel = (Location) dataList.get(j);
                int lastRowNum = sheet.getLastRowNum();
                Row dataRow = sheet.createRow(lastRowNum + 1);
                dataRow.createCell(0).setCellValue(userExcelModel.getRoadcrossing());
                dataRow.createCell(1).setCellValue(userExcelModel.getNode());
                dataRow.createCell(2).setCellValue(userExcelModel.getX());
                dataRow.createCell(3).setCellValue(userExcelModel.getY());
                dataRow.createCell(4).setCellValue(userExcelModel.getLongitude());
                dataRow.createCell(5).setCellValue(userExcelModel.getLatitude());
            }
        }
        else if(type.equals("road")){
            m.put("nowPage",0);
            m.put("limitPageInt",9999999);
            dataList = uavMapper.getRoad(m);
            s = roadCrossing + "路宽.xls";
            //创建数据行并写入值
            for (int j = 0; j < dataList.size(); j++) {
                Road userExcelModel = (Road) dataList.get(j);
                int lastRowNum = sheet.getLastRowNum();
                Row dataRow = sheet.createRow(lastRowNum + 1);
                dataRow.createCell(0).setCellValue(userExcelModel.getRoadcrossing());
                dataRow.createCell(1).setCellValue(userExcelModel.getRoadname());
                dataRow.createCell(2).setCellValue(userExcelModel.getOrder());
                dataRow.createCell(3).setCellValue(userExcelModel.getRoadwidth());
                dataRow.createCell(4).setCellValue(userExcelModel.getRoadtype());
                dataRow.createCell(5).setCellValue(userExcelModel.getRoaddirection());
            }
        }
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("content-Disposition", "attachment;filename=" + URLEncoder.encode(s, "utf-8"));
        response.setHeader("Access-Control-Expose-Headers", "content-Disposition");
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }
//上传数据
    @PostMapping("/readExcel")
    public String readExcel(@RequestParam("file") MultipartFile file){
        String fileName=file.getOriginalFilename();
        System.out.println(file.getOriginalFilename());
        List list = new ArrayList<>();
        try {
//            if(list.get(0) instanceof Location)
            if(fileName.contains("坐标")) {
                list = EasyExcel.read(file.getInputStream(),Location.class,new ModelExcelListener()).sheet().doReadSync();
                for (Object o : list) {
                    uavMapper.insertLocation((Location) o);
                }
                return "redirect:/uav/user/system?msg=location&id=2";
            }
            else if(fileName.contains("路宽")) {
                list = EasyExcel.read(file.getInputStream(),Road.class,new ModelExcelListener()).sheet().doReadSync();
                for (Object o : list) {
                    uavMapper.insertRoad((Road) o);
                }
                return "redirect:/uav/user/system?msg=road&id=2";
            }else {
                return "redirect:/uav/user/system?msg=no&id=2";
            }
//            uavMapper.insertLocation(new Location(1,"1","1",2.0,2.0,"1","1"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/uav/user/system?msg=no&id=2";
    }

//    系统管理
@RequestMapping("/system")
public String system(Model model,String roadCrossing,String nowPage,String limitPage,String id,String msg){
    if(msg!=null&&msg.equals("location"))
        model.addAttribute("msg", "上传坐标成功!");
    else if(msg!=null&&msg.equals("road"))
        model.addAttribute("msg", "上传路宽成功!");
    else if(msg!=null&&msg.equals("no"))
        model.addAttribute("msg", "上传失败!请上传带有坐标或路宽文件名的xls文件!");


    //        System.out.println(nowPage+":nowPage ");
    int limitPageInt=9;
    if(limitPage!=null)limitPageInt=Integer.valueOf(limitPage);

    if(nowPage==null)nowPage="0";
    Map m=new HashMap();
    m.put("roadCrossing",roadCrossing);
//        System.out.println(roadCrossing);
    int count=uavMapper.getRoadCount(m).size();
//        System.out.println("count: "+count);

    int pageSize=count/limitPageInt+1;
    int now=Integer.parseInt(nowPage)<0?0:Integer.parseInt(nowPage);
    now=now>pageSize?pageSize:now;
    m.put("nowPage",now*limitPageInt);
    m.put("limitPageInt",limitPageInt);
    List<Road>list=uavMapper.getRoad(m);
    model.addAttribute("limitPage",limitPageInt);
    model.addAttribute("roads",list);
    model.addAttribute("nowPage",now);
    model.addAttribute("roadCrossing",roadCrossing);
    if(id==null)id="0";
    if(id=="")id="0";
    model.addAttribute("id",id);

//        System.out.println(roadCrossing);
    return "system";
}

    @RequestMapping("/system/updateLocation")
    public String systemUpdateLocation(Location location){
        uavMapper.updateLocation(location);
            return "redirect:/uav/user/detail?id="+location.getId();
    }

    @RequestMapping("/system/deleteLocation")
    public String systemDeleteLocation(Location location,int id){
        uavMapper.deleteLocation(id);
        return "redirect:/uav/user/detail";
    }
    @RequestMapping("/system/insertRoad")
    public String systemInsertRoad(Road road){
//        uavMapper.updateLocation(location);
        System.out.println(road);
        uavMapper.insertRoad(road);
        return "redirect:/uav/user/system";
    }

    @RequestMapping("/system/updateRoad")
    public String systemUpdateRoad(Road road){
        System.out.println(road);
        uavMapper.updateRoad(road);
        return "redirect:/uav/user/system";
    }

    @RequestMapping("/system/deleteRoad")
    public String systemDeleteRoad(Location location,int id){
        uavMapper.deleteRoad(id);
        return "redirect:/uav/user/system";
    }


    @ResponseBody
    @RequestMapping("/g")
    public List<Road> getRoad(){
        List<Road>list=uavMapper.getRoadCount(new HashMap());
        return list;
    }


}
class ModelExcelListener extends AnalysisEventListener {
    private List<Object> datas = new ArrayList<>();
    /**
     * 通过 AnalysisContext 对象还可以获取当前 sheet，当前行等数据
     */
    @Override
    public void invoke(Object data, AnalysisContext context) {
        //数据存储到list，供批量处理，或后续自己业务逻辑处理。
        datas.add(data);
        //根据业务自行处理，可以写入数据库等等
    }
    //所以的数据解析完了调用
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }
}
